﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DSAClient.Core;
using DSAClient.Models.Input;
using DSAClient.Models.Output;
using DSAClient.Properties;
using DSAClient.Utils;
using Qiniu.IO.Resumable;
using Qiniu.RS;

namespace DSAClient
{
    public partial class TemplateForm : BaseForm
    {
        private const int AreaWidth = 299;       //pictureBox控件的最大宽度
        private const int AreaHeight = 201;     //pictureBox控件的最大高度

        public int completedpic = 0;

        public List<SizeImageInfoList> sizeImageInfoList = new List<SizeImageInfoList>();

        public List<ImageInfo> imageInfoList = new List<ImageInfo>();
        public SizeImageInfoList sizeImageInfo = new SizeImageInfoList();
        List<PhotoSizeInfo> psiList;
        public PhotoSizeInfo psi = new PhotoSizeInfo();
        public int currpage = 1;

        ImageForm form;
        public TemplateForm()
        {
            InitializeComponent();
        }

        private void sbtnQuery_Click(object sender, EventArgs e)
        {
            Process.Start("iexplore.exe", "http://shop71252021.taobao.com");
        }

        public Size GetImgSize(Image img)
        {
            Size size = new Size();
            //计算正常比例
            if (img.Width / AreaWidth > img.Height / AreaHeight)//宽度为正常缩放宽度
            {
                size.Height = (int)(img.Width * AreaHeight / AreaWidth);
                size.Width = img.Width;
            }
            else//高度为正常缩放高度
            {
                size.Height = img.Height;
                size.Width = (int)(img.Height * AreaWidth / AreaHeight); ;
            }
            return size;
        }

        internal Bitmap CreateBigPic(Image img)
        {
            Size size = GetImgSize(img);
            Bitmap ob = new Bitmap(size.Width, size.Height);
            using (Graphics g = Graphics.FromImage(ob))
            {

                //Graphics g = Graphics.FromImage(ob);
                g.Clear(Color.White);
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                g.DrawImage(img, (size.Width - img.Width) / 2, (size.Height - img.Height) / 2, img.Width, img.Height);// new Rectangle(0, 0, dWidth, dHeight), new Rectangle(StartX, StartY, dWidth, dHeight), GraphicsUnit.Pixel);
                g.Dispose();
                img.Dispose();
            }
            //ob.Save(@"G:\订阅号\big\" + Guid.NewGuid().ToString() + ".jpg");
            return ob;
        }

        private void sbtnopenpic_Click(object sender, EventArgs e)
        {
            form = (ImageForm)OpenForm("ImageForm");
            if (form.imgSize == "")
            {
                MessageBox.Show("请选择要上传照片的尺寸");
                return;
            }
            if (psiList == null)
            {
                //获取图片尺寸列表
                var result = Api.QueryPhotoSize();
                psiList = result.data;
            }

            psi = psiList.Find((PhotoSizeInfo s) => s.name == form.imgSize && s.picturetype == form.picturetype);

            this.openFileDialog1.Filter = "All files (*.*)|*.*|image files (*.jpg)|*.jpg|image files (*.jpeg)|*.jpeg|image files (*.png)|*.png";
            this.openFileDialog1.Multiselect = true;
            this.openFileDialog1.FileName = "请选择文件";
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string[] FileNames = openFileDialog1.FileNames;
                //form.sizeImageInfo.totalnum = form.sizeImageInfo.totalnum + FileNames.Length;
                //form.sizeImageInfo.surplusnum = form.sizeImageInfo.surplusnum - FileNames.Length;
                //form.ReplaceMessage();

                if (imageInfoList.Count > 0)
                {
                    List<string> files = new List<string>();
                    files.AddRange(FileNames);
                    backgroundWorker1.RunWorkerAsync(files);
                }
                else
                {
                    //int count = FileNames.Length > 8 ? 8 : FileNames.Length;
                    int count = FileNames.Length;
                    List<string> files = new List<string>();
                    for (int i = 0; i < count; i++)
                    {
                        files.Add(FileNames[i]);
                    }
                    backgroundWorker1.RunWorkerAsync(files);

                    form.label2.Text = completedpic.ToString();
                    form.Show();
                    //((ImageForm)form).ShowImage(currpage);
                    sbtnopenpic.Enabled = false;
                    sbtnorderlist.Enabled = false;
                    sbtnsumbitorder.Enabled = false;
                }
            }
        }

        /// <summary>
        /// 调整图片旋转，实现最少留白
        /// </summary>
        /// <param name="imageList"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        protected void AdjustmentImgRotation(List<Image> imageList, float w, float h)
        {
            foreach (Image img in imageList)
            {
                if (img.Width / img.Height > w / h)
                {
                    img.RotateFlip(RotateFlipType.Rotate270FlipNone);
                }
            }
        }

        /// <summary>
        /// 调整图片旋转，实现最少留白
        /// </summary>
        /// <param name="imageList"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        protected void AdjustmentImgRotation(Image image, float w, float h, ImageInfo imageInfo)
        {
            if (image.Width / image.Height < h / w)
            {
                image.RotateFlip(RotateFlipType.Rotate270FlipNone);
            }
            Size size = ParsePictureBoxSize(image, AreaWidth, AreaHeight);
            imageInfo.PicSize = size;
            if (size.Width / w <= size.Height / h)//<=
            {
                int width = size.Width;
                int height = (int)(h * size.Width / w);
                if (imageInfo.Rect.Width == 0 && imageInfo.Rect.Height == 0)
                    imageInfo.Rect = new Rectangle((size.Width - width) / 2, (size.Height - height) / 2, width, height);
            }
            else
            {
                int width = (int)(w * size.Height / h);
                int height = size.Height;
                if (imageInfo.Rect.Width == 0 && imageInfo.Rect.Height == 0)
                    imageInfo.Rect = new Rectangle((size.Width - width) / 2, (size.Height - height) / 2, width, height);
            }
        }

        protected Form OpenForm(string formname)
        {
            Form result = new Form();
            bool isShow = false;
            FormCollection collection = Application.OpenForms;
            foreach (Form form in collection)
            {
                if (form.Name == formname)
                {
                    result = form;
                    isShow = true;
                    break;
                }
            }
            if (!isShow)
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                // 实例化窗体            
                result = assembly.CreateInstance("DSAClient." + formname) as Form;
            }
            return result;
        }

        protected Form OpenForm(string formname, object[] args)
        {
            Form result = new Form();
            bool isShow = false;
            FormCollection collection = Application.OpenForms;
            foreach (Form form in collection)
            {
                if (form.Name == formname)
                {
                    result = form;
                    isShow = true;
                    break;
                }
            }
            if (!isShow)
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                // 实例化窗体            
                result = assembly.CreateInstance("DSAClient." + formname, false, BindingFlags.Default, null, args, null, null) as Form;
            }
            return result;
        }

        private void sbtnorderlist_Click(object sender, EventArgs e)
        {
            sbtnorderlist.BackgroundImage = Resources.openorderlist_a;
            Form gridForm = OpenForm("GridForm");
            this.Hide();
            gridForm.Show();
        }

        private void sbtnbeforepage_Click(object sender, EventArgs e)
        {
            if (currpage > 1)
                currpage = currpage - 1;
            form = (ImageForm)OpenForm("ImageForm");
            form.Show();
            form.ShowImage(currpage);
        }

        private void sbtnnextpage_Click(object sender, EventArgs e)
        {
            int imagepage = Int32.Parse(Math.Ceiling((double)imageInfoList.Count / 8).ToString());
            if (currpage < imagepage)
                currpage = currpage + 1;
            form = (ImageForm)OpenForm("ImageForm");
            form.Show();
            form.ShowImage(currpage);
        }

        private void sbtnhomepage_Click(object sender, EventArgs e)
        {
            currpage = 1;
            form = (ImageForm)OpenForm("ImageForm");
            form.Show();
            form.ShowImage(1);
        }

        private void sbtnendpage_Click(object sender, EventArgs e)
        {
            int imagepage = Int32.Parse(Math.Ceiling((double)imageInfoList.Count / 8).ToString());
            currpage = imagepage;
            Form form = OpenForm("ImageForm");
            form.Show();
            ((ImageForm)form).ShowImage(imagepage);
        }

        private List<PailideConfig> ReadConfig()
        {
            List<PailideConfig> result = new List<PailideConfig>();
            try
            {
                StreamReader rsf = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "\\config\\pailide.dat");
                string strConfig = "";
                while (rsf.Peek() >= 0)
                {
                    strConfig += rsf.ReadLine();
                }
                rsf.Close();
                result = JsonHelper.DeserializeObject<List<PailideConfig>>(strConfig);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
            }
            return result;
        }

        private void EnableButton(bool isenable)
        {
            Invoke((MethodInvoker)delegate
            {
                form.sbtnopenpic.Enabled = isenable;
                form.sbtnhomepage.Enabled = isenable;
                form.sbtnnextpage.Enabled = isenable;
                form.sbtnbeforepage.Enabled = isenable;
                form.sbtnendpage.Enabled = isenable;
                form.sbtnsumbitorder.Enabled = isenable;
                form.sbtnorderlist.Enabled = isenable;
                form.sbtnQuery.Enabled = isenable;
                form.sbtnBatchmap.Enabled = isenable;
            });
        }

        private PailideConfig GetConfig(string size, string pictype)
        {
            var pailideconfig = ReadConfig();
            var config = pailideconfig.Find((PailideConfig p) => p.Size == size && p.PictureType == pictype);
            return config;
        }

        private void sbtnsumbitorder_Click(object sender, EventArgs e)
        {
            if (form == null)
            {
                MessageBox.Show("请选择要上传的照片", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            //判断是否符合上传条件
            if (CheckUploadCondition())
            {
                //计算图片总数量
                int total = 0;
                foreach (SizeImageInfoList s in sizeImageInfoList)
                {
                    //if (s.producttype == "普通照片")
                    //{
                    if (s.size == "3寸" || s.size == "4寸")
                    {
                        var config = GetConfig(s.size, s.producttype);
                        total += ImageHelper.ParseImgNum(config, s.imageInfoList);
                    }
                    else
                    {
                        foreach (ImageInfo imageInfo in s.imageInfoList)
                        {
                            //处理图片
                            if (imageInfo != null && imageInfo.ImgPath != "")
                            {
                                total++;
                            }
                        }
                    }
                }
                form.panel18.Location = new Point(0, 161);
                form.p = new XControls.OpaqueLayerControl(form.panel18) { Text = "Processing...", Maximum = total, Value = 0, LoadingWidth = 450, LoadingHeight = 32 };
                form.p.Visible = form.panel18.Visible = true;

                BackgroundWorker bk = new BackgroundWorker();
                bk.DoWork += delegate
                {
                    EnableButton(false);
                    string path = AppDomain.CurrentDomain.BaseDirectory + "\\ImgTemplate\\";
                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);
                    AppReportManager.Instance.AddListener<QiniuUploadLog>(doLog);
                    AppReportManager.Instance.AddListener<QiniuUploadResult>(doResult);

                    //CheckUploadCondition();
                    List<ImageSubmitInfo> imageSubmitInfoList = new List<ImageSubmitInfo>();
                    List<string> filepathList = new List<string>();
                    foreach (SizeImageInfoList s in sizeImageInfoList)
                    {
                        if (s.producttype == "普通照片" || s.producttype == "正方形")
                        {
                            if (s.size == "3寸" || s.size == "4寸")
                            {
                                var pailideconfig = ReadConfig();
                                var config = pailideconfig.Find((PailideConfig p) => p.Size == s.size && p.PictureType == s.producttype);
                                ImageHelper.MergerImg(config, s.imageInfoList, s.oid, form);
                            }
                            else
                            {
                                foreach (ImageInfo imageInfo in s.imageInfoList)
                                {
                                    //处理图片
                                    if (imageInfo != null && imageInfo.ImgPath != "")
                                    {
                                        Image img = null;
                                        if (!imageInfo.IsCut)
                                        {
                                            img = Image.FromFile(imageInfo.ImgPath);
                                            AdjustmentImgRotation(img, psi.height, psi.width, imageInfo);
                                            img = ImageHelper.CreateBigPic(img, s.imgSize);
                                            imageInfo.Rect = new Rectangle(new Point(0, 0), imageInfo.PicSize);
                                        }
                                        else
                                        {
                                            img = Image.FromFile(imageInfo.ImgPath);
                                            AdjustmentImgRotation(img, psi.height, psi.width, imageInfo);
                                            //img = (Image)imageInfo.Img.Clone();
                                        }
                                        ImageHelper.KiCut(img, path + imageInfo.filepath + ".jpg",
                                                    imageInfo.Rect.X * img.Width / imageInfo.PicSize.Width,
                                                    imageInfo.Rect.Y * img.Height / imageInfo.PicSize.Height,
                                                    img.Width * imageInfo.Rect.Width / imageInfo.PicSize.Width,
                                                    img.Height * imageInfo.Rect.Height / imageInfo.PicSize.Height);
                                        var aa = new QiniuUploadTask(path + imageInfo.filepath + ".jpg", imageInfo, s.oid).Run(null);
                                        form.p.Invoke((MethodInvoker)delegate
                                        {
                                            form.p.Value++;
                                            form.p.Text = "已经上传" + ((float)(form.p.Value) / (float)(total)) * 100 + "%,请耐心等待！！";
                                            Application.DoEvents();
                                        });
                                    }
                                }
                            }
                        }
                        else
                        {
                            var pailideconfig = ReadConfig();
                            var config = pailideconfig.Find((PailideConfig p) => p.Size == s.size && p.PictureType == "拍立得");
                            ImageHelper.MergerImg(config, s.imageInfoList, s.oid, form);
                        }
                    }
                };
                bk.RunWorkerCompleted += delegate
                {
                    form.p.Visible = form.panel18.Visible = false;
                    form.p = null;
                    EnableButton(true);

                    //更新数据库，订单状态已完成
                    if (sizeImageInfoList.Count > 0)
                    {
                        Api.UpdateTrade(new object[] { sizeImageInfoList[0].no, imageSubmitInfoList });
                    }
                    Console.WriteLine("全部上传成功!");

                    //关闭所有窗体
                    FormCollection collection = Application.OpenForms;
                    List<Form> temp = new List<Form>();
                    foreach (Form f in collection)
                    {
                        if (f.Name != "Main")
                            temp.Add(f);
                    }
                    foreach (Form f in temp)
                    {
                        f.Dispose();
                    }

                    Form frm = OpenForm("Main");
                    frm.Show();

                };
                bk.ProgressChanged += delegate
                {

                };
                bk.RunWorkerAsync();
            }
            else
            {
                if (form.p != null)
                {
                    form.p.Visible = form.panel18.Visible = false;
                    form.p = null;
                }
                EnableButton(true);
            }

        }

        private bool CheckUploadCondition()
        {
            bool result = true;
            if (sizeImageInfoList.Count == 0)
            {
                result = false;
                MessageBox.Show("请选择要上传的照片", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            foreach (SizeImageInfoList sii in sizeImageInfoList)
            {
                if (sii.imageInfoList.Count == 0)
                {
                    result = false;
                    MessageBox.Show("您的订单还没有上传照片", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    break;
                }
                if (sii.surplusnum < 0)
                {
                    result = false;
                    MessageBox.Show("您选择的照片数量超出了订单照片数量", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    break;
                }
                if (sii.totalnum < sii.ordernum)
                {
                    result = false;
                    MessageBox.Show("您选择的照片数量少于订单照片数量", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    break;
                    //if (MessageBox.Show("您选择的照片数量少于订单照片数量,是否确定上传(请检查是否上传图片有小于" + Convert.ToInt32(ConfigurationSettings.AppSettings["MinSize"]) / 1024 + "KB的文件)", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Cancel)
                    //{
                    //    result = false;
                    //    //return;
                    //    break;
                    //}
                }
            }
            return result;
        }

        void doLog(QiniuUploadLog qiniuUploadLog)
        {
            Console.WriteLine(string.Format("[{0}].{1}", DateTime.Now.ToString("HH:mm:ss"), qiniuUploadLog.msg));
        }
        List<ImageSubmitInfo> imageSubmitInfoList = new List<ImageSubmitInfo>();
        /// <summary>
        /// 存储数据库
        /// </summary>
        /// <param name="result"></param>
        void doResult(QiniuUploadResult qnresult)
        {
            ImageSubmitInfo data = new ImageSubmitInfo();
            ImageInfo imageInfo = (ImageInfo)(qnresult.tag ?? new ImageInfo());
            data.oid = qnresult.oid;
            data.pid = Guid.NewGuid().ToString().Replace("-", "");
            data.url = qnresult.url;
            data.num = imageInfo.ImgNum;
            imageSubmitInfoList.Add(data);
            //var result = Api.SaveOrderImage(data);
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            List<string> FileNames = (List<string>)e.Argument;
            if (!Directory.Exists(Application.StartupPath + @"\Log\"))
            {
                Directory.CreateDirectory(Application.StartupPath + @"\Log\");
            }
            FileStream fs = new FileStream(Application.StartupPath + @"\Log\" + form.sizeImageInfo.errorfile + ".txt", FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);

            for (int i = 0; i < FileNames.Count; i++)//string fileName in FileNames)
            {
                FileInfo fileInfo = new FileInfo(FileNames[i]);
                if (fileInfo.Length < Convert.ToInt32(ConfigurationSettings.AppSettings["MinSize"]))
                {
                    //记录到文本文件中
                    //开始写入
                    sizeImageInfo.iserror = true;
                    sw.Write(FileNames[i] + "的文件大小【" + (fileInfo.Length / 1024f) + "KB】小于最低要求【20KB】大小，请重新上传\r\n");
                    continue;
                }
                if (fileInfo.Length > Convert.ToInt32(ConfigurationSettings.AppSettings["MinSize"]) && fileInfo.Length < 51200)
                {
                    sizeImageInfo.iserror = true;
                    sw.Write(FileNames[i] + "的文件大小【" + (fileInfo.Length / 1024f) + "KB】小于【50KB】，如果冲印将影响冲印效果!!!\r\n");
                }
                ImageInfo imageInfo = new ImageInfo();

                imageInfo.ImgPath = FileNames[i];
                imageInfo.IsCut = true;
                imageInfo.CanMove = false;

                form.Invoke((MethodInvoker)delegate
                {
                    form.lbtotalnum.Text = (++form.sizeImageInfo.totalnum).ToString(); //totalnum.ToString();
                    form.lbsurplusnum.Text = (--form.sizeImageInfo.surplusnum).ToString(); //surplusnum.ToString();
                    Application.DoEvents();
                });

                //AdjustmentImgRotation(imageInfo.Img, psi.height, psi.width, imageInfo);

                //imageInfo.Img = CreateBigPic(image);
                //imageInfo.Img = image;
                imageInfo.filepath = Guid.NewGuid().ToString().Replace("-", "");
                imageInfo.ImgNum = 1;
                imageInfo.IsOpenPic = false;

                imageInfoList.Add(imageInfo);

                bw.ReportProgress(completedpic++);
                GC.Collect();
                Thread.Sleep(100);
            }
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("处理图片发生错误，请联系管理员");
            }
            else if (e.Cancelled)
            {
                MessageBox.Show("处理图片已被取消，请联系管理员");
            }
            else
            {
                sbtnopenpic.Enabled = true;
                sbtnorderlist.Enabled = true;
                sbtnsumbitorder.Enabled = true;
                if (sizeImageInfo.iserror)
                {
                    form.llbLog.Visible = true;
                }
                else
                {
                    form.llbLog.Visible = false;
                }
            }

        }

        void UpdateProgress(object sender, ProgressChangedEventArgs e)
        {
            try
            {
                int progress = e.ProgressPercentage;
                form.label2.Text = (progress + 1).ToString();
                int picIndex = (currpage - 1) * 8;

                for (int i = 1; i < 9; i++)
                {
                    Control control = form.Controls.Find("pictureBox" + (i).ToString(), true)[0];
                    PictureBox pb = (PictureBox)control;
                    if (pb.Image == null)
                    {

                        Control panelcontrol = form.Controls.Find("panel" + (i).ToString(), true)[0];
                        Image img = Image.FromFile(imageInfoList[picIndex + i - 1].ImgPath);
                        AdjustmentImgRotation(img, psi.height, psi.width, imageInfoList[picIndex + i - 1]);
                        ParsePictureBoxSize(img, pb, 299, 201, panelcontrol.Size);//imageInfoList[picIndex + i - 1].Img

                        pb.Image = img; //imageInfoList[picIndex + i - 1].Img;
                        break;
                    }
                }
            }
            catch { }
        }

        /// <summary>
        /// 计算图片框的大小和位置
        /// </summary>
        /// <param name="img"></param>
        /// <param name="pb"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="panelSize"></param>
        public void ParsePictureBoxSize(Image img, PictureBox pb, int width, int height, Size panelSize)
        {
            Size size = new Size();
            if ((float)img.Width / (float)img.Height < (float)width / (float)height)
            {
                size.Height = height;
                size.Width = img.Width * height / img.Height;
            }
            else
            {
                size.Width = width;
                size.Height = img.Height * width / img.Width;
            }
            pb.Size = size;
            Point p = new Point(((panelSize.Width - size.Width) / 2), ((panelSize.Height - size.Height) / 2));
            pb.Location = p;
        }

        /// <summary>
        /// 计算图片框的大小和位置
        /// </summary>
        /// <param name="img"></param>
        /// <param name="pb"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="panelSize"></param>
        public Size ParsePictureBoxSize(Image img, int width, int height)
        {
            Size size = new Size();
            if ((float)img.Width / (float)img.Height < (float)width / (float)height)
            {
                size.Height = height;
                size.Width = img.Width * height / img.Height;
            }
            else
            {
                size.Width = width;
                size.Height = img.Height * width / img.Width;
            }
            return size;
        }
    }
}
